<template>
  <div class="wrap">
    <div class="top">
      <div class="name">应用名称：{{ app_name }}</div>
    </div>
    <div class="permission-input-wrap">
      <el-input
        v-model="filterText"
        style="width: 400px; margin-bottom: 10px"
        placeholder="请输入关键字进行过滤"
      />
    </div>
    <el-button type="primary" plain @click="handleCheckAll">全选</el-button>
    <el-button type="success" plain @click="handleReverseCheck">反选</el-button>
    <el-button type="warning" plain @click="handleClear">清空</el-button>
    <el-button type="primary" class="sub-btn" @click="handleSub"
      >提交<el-icon class="el-icon--right"><Upload /></el-icon
    ></el-button>
    <el-tree
      ref="tree"
      style="max-width: 600px; margin-top: 10px"
      :data="data"
      show-checkbox
      node-key="id"
      :default-expanded-keys="[]"
      :default-checked-keys="[]"
      :props="defaultProps"
      :filter-node-method="handleFilterNode"
    />
  </div>
</template>

<script setup>
import { reactive, ref, getCurrentInstance, watch, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { postData } from '@/http/request'
import { ElMessage } from 'element-plus'

let router = useRouter()
let route = useRoute()
const resData = ref({})

let app_id = route.query.app_id
let app_name = route.query.app_name
const defaultProps = ref({
  children: 'children',
  label: 'label',
})

let checkedData = ref([])

let allCheckedAll = ref([])

let baseData = ref([])

const { proxy } = getCurrentInstance()

let data = ref([])

// 筛选
let filterText = ref('')
watch(filterText, (val) => {
  proxy.$refs.tree.filter(val)
})

function handleData(key) {
  allCheckedAll.value = []
  checkedData.value = []
  postData('/api/list', {
    status: 0,
    sort_name: 'all',
    auth_for: 'app',
    auth_for_id: app_id || '',
    with_details: 0,
  })
    .then((res) => {
      resData.value = res
      baseData.value = []
      let datas = Array.from(resData.value?.datas?.sorts || [])
      for (let i = 0; i < datas.length; i++) {
        let sortData = datas[i]
        sortData['label'] = sortData['sort_desc']
        sortData['id'] = sortData['sort_name']
        baseData.value.push(sortData['sort_name'])
        sortData['children'] = sortData['apis']
        let children = sortData['children'] || []
        for (let j = 0; j < children.length; j++) {
          children[j]['id'] = children[j]['api_name']
          children[j]['label'] = children[j]['api_desc']
          if (
            typeof children[j]['authorized'] != 'undefined' &&
            children[j]['authorized'] == 1
          ) {
            checkedData.value.push(children[j]['id'])
          }
          allCheckedAll.value.push(children[j]['id'])
        }
      }
      data.value = datas
      setTimeout(() => {
        proxy.$refs.tree.setCheckedKeys(Array.from(checkedData.value), false)
      }, 0)
    })
    .catch((err) => {
      console.log('喜欢大美猴')
    })
}

// 提交
function handleSub() {
  let checkedData = proxy.$refs.tree.getCheckedKeys() || []
  let postDataArr = checkedData.filter((item) => !baseData.value.includes(item))
  console.log(checkedData)
  postData('/dev/app/api/set', {
    app_id: app_id,
    apis: postDataArr,
  })
    .then((res) => {
      if (res.code == 0) {
        ElMessage({
          type: 'success',
          message: '设置成功',
        })
      } else {
        ElMessage({
          type: 'error',
          message: '设置失败',
        })
      }
    })
    .catch((err) => {
      ElMessage({
        type: 'error',
        message: '请稍后重试',
      })
    })
}

// 全选
function handleCheckAll() {
  let allKeys = allCheckedAll.value || []
  proxy.$refs.tree.setCheckedKeys(allKeys)
}

// 反选
function handleReverseCheck() {
  let allKeys = allCheckedAll.value || []
  let checkedData = proxy.$refs.tree.getCheckedKeys() || []
  let reverseCheckKeys = allKeys.filter((item) => !checkedData.includes(item))
  proxy.$refs.tree.setCheckedKeys(reverseCheckKeys)
}

//清空
function handleClear() {
  let allKeys = []
  proxy.$refs.tree.setCheckedKeys(allKeys)
}

// 过滤
function handleFilterNode(value, data) {
  if (!value) return true
  return data.label.includes(value)
}

onMounted(() => {
  handleData()
})
</script>

<style scoped>
.title {
  width: 100%;
  height: 40px;
  line-height: 40px;
  position: relative;
  /* background: #c0dee2; */
  font-size: 14px;
  margin-left: 10px;
  /* border-radius: 12px 12px 0 0; */
  /* font-weight: bold; */
}

.title::before {
  content: '';
  width: 2px;
  height: 16px;
  background: #676a6d;
  position: absolute;
  top: 12px;
  left: 0;
}

.title span {
  float: left;
  color: #676a6d;
  margin-left: 25px;
}
.name {
  margin-bottom: 15px;
  color: #333;
}

.el-button-group .el-button {
  border-right: none;
}
.permission-input-wrap {
  margin-top: 10px;
  margin-bottom: 10px;
}
.sub-btn {
  margin-left: 30px;
}
</style>
